#pragma once
#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <sys/wait.h>
#include <pthread.h>
#include <functional>
#include "InetAddr.hpp"
#include "Log.hpp"
#include "ThreadPool.hpp"

using namespace std;

const static int defaultsockfd = -1;
const static int backlog = 16;

using task_t = function<void()>;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR,
    USAGE_ERROR
};

class TcpServer;// 声明
class ThreadData
{
public:
    ThreadData(int fd, InetAddr addr, TcpServer *s):sockfd(fd), clientaddr(addr),self(s)
    {}
public:
    int sockfd;
    InetAddr clientaddr;
    TcpServer *self;
};

class TcpServer
{
public:
    TcpServer(uint16_t port) : _port(port), _listensock(defaultsockfd), _isrunning(false)
    {
    }
    void InitServer()
    {
        // 创建流式套接字
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            LOG(FATAL, "socket error");
            exit(SOCKET_ERROR);
        }
        LOG(INFO, "socket create success, sockfd: %d", _listensock);

        // bind 先填充结构体
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;

        int n = bind(_listensock, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(FATAL, "bind error");
            exit(BIND_ERROR);
        }
        LOG(INFO, "bind create success, sockfd: %d", _listensock);

        // 监听listen —— 先建立连接，启动后等待客户
        n = listen(_listensock, backlog);
        if (n < 0)
        {
            LOG(FATAL, "listen error");
            exit(LISTEN_ERROR);
        }
        LOG(INFO, "listen create success, sockfd: %d", _listensock);
    }
    void Server(int sockfd, InetAddr client)
    {
        LOG(DEBUG, "get a new link sockfd: %d, %s:%d", sockfd, client.Ip().c_str(), to_string(client.Port()));
        string clientaddr = "[" + client.Ip() + ":" + to_string(client.Port()) + "]# ";
        while (true)
        {
            char inbuffer[1024];
            ssize_t n = read(sockfd, inbuffer, sizeof(inbuffer));
            if (n > 0) // 读成功
            {
                inbuffer[n] = 0;
                cout << clientaddr << inbuffer << endl;

                string echo_string = "[server echo]# ";
                echo_string += inbuffer;

                write(sockfd, echo_string.c_str(), echo_string.size());
            }
            else if (n == 0) // 读停止 && 关闭连接
            {
                LOG(WARNING, "%s quit", clientaddr.c_str());
                break;
            }
            else // 读失败
            {
                LOG(ERROR, "read error");
                break;
            }
        }
        close(sockfd); // 防止文件描述符泄漏 不要写在循环里面！
    }
    static void *HandlerTask(void *args)
    {
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData*>(args);
        td->self->Server(td->sockfd, td->clientaddr);
        delete td;
        return nullptr;
    }
    void Loop()
    {
        _isrunning = true;
        // 不能直接获取数据，先获取连接
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensock, (struct sockaddr *)&peer, &len);
            if (sockfd < 0)
            {
                LOG(WARNING, "listen error");
                continue;
            }

            // Version 4 - 线程池
            task_t t = bind(&TcpServer::Server, this, sockfd, InetAddr(peer));
            ThreadPool<task_t> *tp = new ThreadPool<task_t>();
            tp->InitThreadPool();
            tp->Start();
            tp->Enqueue(t);
        }

        _isrunning = false;
    }
    TcpServer()
    {
        if (_listensock > defaultsockfd)
            close(_listensock);
    }

private:
    int _listensock;
    uint16_t _port;
    bool _isrunning;
};